<template>
	<DataList ref="DataListRef" :api="getListByPage" :columns="topicColumns" @onOperation="onOperation"
		:query="queryUserForm" />

	<!-- 编辑弹窗 -->
	<el-dialog v-model="showEdit" title="编辑圈子" width="30%">
		<el-form :model="dataForm" label-width="120px">
			<el-form-item label="名称">
				<el-input v-model="dataForm.name" />
			</el-form-item>
			<el-form-item label="类目">
				<el-select v-model="dataForm.class_id" placeholder="选择圈子类目" style="width: 100%;">
					<el-option v-for="item in topicClassList" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="状态">
				<el-radio-group v-model="dataForm.status">
					<el-radio :label="2">推荐</el-radio>
					<el-radio :label="1">正常</el-radio>
					<el-radio :label="0">关闭</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit">保存</el-button>
				<el-button @click="showEdit = false">取消</el-button>
			</el-form-item>
		</el-form>
	</el-dialog>
</template>
<script setup>
import { getListByPage, topicDelete, topicInfo, topicSave, classList } from "@/api/topic";
import { topicColumns, queryUserForm } from "./constant"
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref, onMounted } from 'vue';

const DataListRef = ref(null)
const showEdit = ref(false)
const topicClassList = ref([])

const dataForm = reactive({
	id: 0,
	name: '',
	status: '',
	class_id: ''
})

onMounted(() => {
	getTopicClass()
})

// 点击操作列回调函数
function onOperation(e) {
	let { key, rowData } = e;

	// 编辑
	if (key == 'edit') {
		showEdit.value = true;
		dataForm.id = 0;
		dataForm.name = '';
		dataForm.status = '';
		getTopicInfo(rowData.row.id);
	}
	// 删除
	if (key == 'delete') {
		onTopicDelete([rowData.row.id])
	}
}

// 删除帖子
function onTopicDelete(ids) {
	ElMessageBox.confirm('是否确认删除？', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		topicDelete({
			ids
		}).then(res => {
			if (res.code == 1) {
				ElMessage({
					type: 'success',
					message: '删除成功',
				})

				DataListRef.value.getList()
			}
		})
	})
}

function getTopicInfo(id) {
	topicInfo({ id }).then(res => {
		const topicInfo = res.result;

		dataForm.id = topicInfo.id;
		dataForm.name = topicInfo.name;
		dataForm.status = topicInfo.status;
		dataForm.class_id = topicInfo.class_id ? topicInfo.class_id : '';
	})
}

function onSubmit() {
	topicSave(dataForm).then(res => {
		if (res.code == 1) {

			ElMessage({
				type: 'success',
				message: '保存成功',
			})

			DataListRef.value.getList();
			showEdit.value = false;
		}
	})
}

// 获取圈子类目列表
function getTopicClass() {
	classList().then(res => {
		topicClassList.value = res.result;

		res.result.forEach(topic => {
			topicColumns[0].options[topic.id] = topic.name;
		});

		queryUserForm[0].options = res.result;
	})
}
</script>
<style></style>